<?php

class Model {
    /* Nombre de Tabla en Base de Datos */

    static $table = "table_name";


    /*
     * @save 
     * Save in Database checheking the id
     */

    public function save() {
        $db = new Dbaccess();

        $propiedades = get_object_vars($this);

        /* Comprobamos si existe en la tabla */
        if (!empty($this->id) && $db->exist('select * from ' . $this::$table . ' where `id`=' . $this->id)) {
            $query = "update `" . $this::$table . "` set ";
            foreach ($propiedades as $key => $value) {
                if ($key != "id") {
                    $query.= " " . $key . '="' . $value . '" ';
                }
            }
            $query .= 'where `id`=' . $this->id;
            $db->query($query);
        } else {
            $query = "insert into `" . $this::$table . "` set ";
            foreach ($propiedades as $key => $value) {
                if ($key != "id") {
                    $query.= " " . $key . '="' . $value . '" ';
                }
            }
            $db->query($query);
            $this->id = $db->last();
        }
        $db->close();
    }

    public static function getOneById($class, $id) {
        $db = new Dbaccess();
        $query = 'select * from `' . $class::$table . '` where id=' . $id;
        $result = $db->query($query);
        $object = new $class();
        while ($row = $db->iterator($result)) {
            foreach ($row as $key => $value) {
                $object->$key = $value;
            }
        }
        $db->close();
        return $object;
    }

    public static function getAll($class) {
        $db = new Dbaccess();
        $query = 'select * from `' . $class::$table . '`';

        $result = $db->query($query);

        $object = new $class();
        $objects = array();

        while ($row = $db->iterator($result)) {
            foreach ($row as $key => $value) {
                $object->$key = $value;
            }
            $objects[] = $object;
        }
        $db->close();
        return $objects;
    }

    protected function delete() {
        $db = new Dbaccess();
        $query = 'delete `' . $this::$table . '` where id="' . $this->id . '"';

        $db->query($query);
        if ($db->rowsAffected() < 1)
            die("I couldn't delete the object in database");
        else
            return true;
        $db->close();
    }

}

?>
